package cn.didi.feidi.androidorder.fragment.personal;


import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.xw.repo.XEditText;

import java.util.HashMap;
import java.util.Map;

import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.activity.personal.PersonFindBackPasswordActivity;
import cn.didi.feidi.androidorder.activity.personal.PersonRegisterActivity;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.api.ErrorEvent;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.fragment.FeidiBaseFragment;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.model.LoginReturnResultByUser;
import cn.didi.feidi.androidorder.util.AppUtil;
import cn.didi.feidi.androidorder.util.DataCheckUtil;
import cn.didi.feidi.androidorder.util.MD5Util;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

import static cn.didi.feidi.androidorder.R.id.person_register_tv;

@RuntimePermissions
public class PersonLoginFragment extends FeidiBaseFragment {

    private static final String TAG = "PersonLoginFragment";
    private XEditText phoneOrFeidiNum;
    private XEditText accountPassword;
    private TextView login;
    private TextView register;
    private TextView forgetPassword;
    private String phoneImei;

    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static PersonLoginFragment newInstance(Bundle bundle) {
        PersonLoginFragment fragment = new PersonLoginFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }

    @NeedsPermission(Manifest.permission.READ_PHONE_STATE)
    public void setImei() {
        phoneImei = AppUtil.getDeviceId(mActivity);
    }

    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_person_login, container, false);
        Log.d(TAG, "initFragment");
        return rootView;
    }


    @Override
    protected void initViews(View rootView) {
        phoneOrFeidiNum = (XEditText) rootView.findViewById(R.id.person_login_phoneOrFeidiNum_input);
        accountPassword = (XEditText) rootView.findViewById(R.id.person_login_account_password_input);
        login = (TextView) rootView.findViewById(R.id.person_login_tv);
        register = (TextView) rootView.findViewById(person_register_tv);
        forgetPassword = (TextView) rootView.findViewById(R.id.person_login_forget_password);
    }

    @Override
    protected void initData() {
        PersonLoginFragmentPermissionsDispatcher.setImeiWithCheck(this);
    }

    @Override
    protected void addListener() {
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String phone = phoneOrFeidiNum.getText().toString();

                //检验手机
                if (!DataCheckUtil.isRightPhoneNumber(phone) && !DataCheckUtil.isRightFeidiAccount(phone)){
                    makeToast("输入手机号或飞滴号");
                    return;
                }

                //检验密码
                String password = accountPassword.getText().toString();

                if (!AppUtil.checkPassword(password)) {
                    makeToast("输入正确的密码");
                    return;
                }

                //进行登陆
                Map<String, String> params = new HashMap<>();

                setImei();
                params.put("account", phone.trim());
                params.put("password", MD5Util.GetMD5Code32Bit(password.trim()));
                params.put("imei", phoneImei);

                executeRequest(new AppActionRequest<LoginReturnResultByUser>(Api.LOGIN, params,
                        new TypeToken<ApiResponse<LoginReturnResultByUser>>() {
                        }.getType(), new ActionCallbackListener<LoginReturnResultByUser>() {
                    @Override
                    public void onSuccess(String message, LoginReturnResultByUser data) {
                        if (data != null) {
                            ////  : 2017/7/18 建立长连接
                            Log.d(TAG, "登陆成功: " + data.getLoginInfo().getToken() + " : " + data.getLoginInfo().getUid());
                            //  : 2017/7/19 登陆成功，跳到下一个activity
                            //保存用户必要信息
                            UserManager.setUserId(data.getLoginInfo().getUid());
                            UserManager.setToken(data.getLoginInfo().getToken());
                            UserManager.setPhone(data.getUser().getPhoneNumber());

                            UserManager.setName(data.getUser().getName());
                            UserManager.setHeadPortrait(data.getUser().getPortraitUrl());
                            UserManager.setFeidiAccount(data.getUser().getFeidiAccount());
                            UserManager.setFeidiAccountStatus(data.getUser().getFeidiAccountStatus());

                            if (data.getUser().getTouchDeliverId() != null&&!"".equals(data.getUser().getTouchDeliverId()))
                                UserManager.setWaterDelverId(data.getUser().getTouchDeliverId());
                            //判断是否设置支付密码
                            if (data.getUser().getPayPwd().equals("0")){
                                UserManager.setPayPassword(true);
                            }else{
                                UserManager.setPayPassword(false);
                            }

                            mActivity.userLogin();

                            goHome();
                        } else {
                            makeToast("success" + message);
                            Log.d(TAG, message);
                        }
                    }

                    @Override
                    public void onFailure(int errorEvent, String message) {
                        Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);

                        switch (errorEvent) {
                            case ErrorEvent.NONE_USER:
                                //不存在当前用户
                                invalidPhone();
                                break;
                            case ErrorEvent.WRONG_PASSWORD:
                                //密码错误
                                invalidPassword();
                                break;
                            case ErrorEvent.WRONG_PHONE_NUMBER:
                                makeToast("账号名为手机号");
                                break;
                            case ErrorEvent.PARAM_NULL:
                                makeToast("参数为空");
                                break;
                            case ErrorEvent.PARAM_ILLEGAL:
                                makeToast("参数为空");
                                break;
                            case ErrorEvent.PARAM_ACCESS_FAILURE:
                                makeToast("网络异常，访问失败");
                                break;
                            case ErrorEvent.ACCOUND_CANCLE:
                                makeToast("该账号已注销，请联系客服");
                                break;
                            default:
                                makeToast("未知错误");
                                break;
                        }
                    }
                }));
            }
        });
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), PersonRegisterActivity.class);
                startActivity(intent);
            }
        });
        forgetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), PersonFindBackPasswordActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 跳转到主页
     */
    private void goHome() {
//        Intent intent = new Intent(mActivity, MainActivity.class);
//        startActivity(intent);
        mActivity.finish();
    }

    /**
     * 密码错误
     */
    private void invalidPassword() {
        makeToast("密码错误");
    }

    /**
     * 不存在当前用户
     */
    private void invalidPhone() {
        makeToast("不存在当前用户");
    }
}
